import type { ImageSourceSpecification } from 'mapbox-gl';
import type { Mapless } from '..';
import type { IdHubType } from '../core/IdHub';
import IdHub from '../core/IdHub';
import { Manager } from '../core/manager';
import type { Coordinates } from '../extensions/mapless.adapter';
import type { ManagerOptions } from '../index.d';

type ImageDataIdHubType = IdHubType & {
  sourceId: string;
  layerId: string;
};

export default class ImageDataManager extends Manager {
  constructor(mapless: Mapless, options?: ManagerOptions) {
    super(mapless, options, 'imagedata');
    this.onInitialized();
  }

  override createIdHub(_idHub?: IdHubType) {
    const newHub = new IdHub({
      layers: {
        layerId: 'dzmap-imagedata-layer',
      },
      sources: {
        sourceId: 'dzmap-imagedata-source',
      },
    }) as ImageDataIdHubType;
    super.createIdHub(newHub);
  }

  override initLayers() {
    if (!this.mapless) return;
    // 添加数据源
    // imagedata 特殊不能按照之前的方式预添加
    // TODO 要想一致处理需要预添加一个1像素的透明图片
  }

  drawImageData(coordinates: Coordinates, imageUrl: string) {
    if (!this.mapless?.getSource(this.idHub?.sourceId)) {
      const sourceSpecification: ImageSourceSpecification = {
        type: 'image',
        url: imageUrl,
        coordinates,
      };
      this.mapless?.addSource(this.idHub?.sourceId, sourceSpecification);
    } else {
      this.mapless?.updateImage(this.idHub?.sourceId, {
        url: imageUrl,
        coordinates,
      });
    }
    if (!this.mapless?.getLayer(this.idHub?.layerId)) {
      this.mapless?.addLayer({
        id: this.idHub?.layerId,
        type: 'raster',
        source: this.idHub?.sourceId,
        paint: {
          'raster-opacity': 1,
          'raster-fade-duration': 1,
        },
      });
    }
  }
}

export const attachImageData = (mapless: Mapless | undefined, name?: string) =>
  mapless?.use(ImageDataManager, name);
export const getImageData = (mapless: Mapless | undefined, name?: string) =>
  mapless?.get(ImageDataManager, name);
export const detachImageData = (mapless: Mapless | undefined, name?: string) =>
  mapless?.unuse(ImageDataManager, name);
